package com.zhongyouyun.other.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.support.spring.stat.SpringStatUtils;
import com.alibaba.fastjson.JSON;
import com.zhongyouyun.admin.model.UserModel;
import com.zhongyouyun.config.RedisConfig;
import com.zhongyouyun.other.model.TokenUtil;
import com.zhongyouyun.utils.SpringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class CORSAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger logger = LoggerFactory.getLogger(CORSAuthenticationFilter.class);

    public CORSAuthenticationFilter() {
        super();
    }
  @Override
    public boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse response, Object mappedValue) {
        Subject subject = SecurityUtils.getSubject();
        String sessionId = null;
        if (ObjectUtil.isNotNull(subject.getSession().getId())) {
            sessionId = subject.getSession().getId().toString();
        }
        RedisConfig redisConfig = SpringUtil.getBean(RedisConfig.class);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String newtoken = request.getHeader(TokenUtil.tokenHeard);
        if (null == newtoken || "".equals(newtoken)) {
            System.out.println("-------------------token为空");
            return false;
        }
        //验证token的真实性
        try {
            System.out.println(newtoken);
            TokenUtil.getTokenBody(newtoken);
            if (ObjectUtil.isNotNull(sessionId)) {
                if (ObjectUtil.isNotNull(redisConfig.get(sessionId))) {
                    String token = redisConfig.get(sessionId).toString();
                    System.out.println(token);
                    if(!token.equals(newtoken)){
                        return false;
                    }
                }
            }
            UserModel userModel = (UserModel) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
            if(ObjectUtil.isNull(userModel)){
                 return  false;
            }

            //这里可能验证token的效

        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("----------------token有问题");
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        res.setHeader("Content-type", "text/html;charset=UTF-8");
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("status", 2);
        map.put("msg", "未登录");
        writer.write(JSON.toJSONString(map));
        writer.close();
        return false;
    }
}